package com.jinzecloud.reportapproval.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jinzecloud.reportapproval.bean.Admin;
import com.jinzecloud.reportapproval.mapper.AdminMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private AdminMapper userInfoMapper;
    @Resource
    private HttpServletResponse response;

    @Override
    public UserDetails loadUserByUsername(String account) {
        Admin userInfo = userInfoMapper.selectOne(new QueryWrapper<Admin>().eq("ad_user_name", account));
        if (userInfo == null) {
            response.setContentType("application/json:charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            Map map = new HashMap();
            map.put("code", 401);
            map.put("msg", "登录失败,请重新登录");
            String subject = JSONObject.toJSONString(map);
            try {
                response.getWriter().append(subject);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            return new org.springframework.security.core.userdetails.User(userInfo.getAdUserName(), userInfo.getAdPassWord(), true, true, true, true, getAuthorities(userInfo));
            // return new org.springframework.security.core.userdetails.User(userInfo.getAccount(), userInfo.getPassword(), true, true, true, true,getAuthorities(userInfo));
        }
        return null;
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Admin userInfo) {
        Set<GrantedAuthority> authorities = new HashSet<>();
        authorities.add(new SimpleGrantedAuthority("userInfo.getBlaccount()"));
        return authorities;
    }

}